﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Text;   


public partial class QualifyResultsPerMachine : System.Web.UI.Page
{
    public const char SCORE_DELIMITER = ',';
    public string HTMLOUT;
    public int[] Scores;
    public Tournament oTour;
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            Scores = (int[])Session["QualifyScores"];

            Configuration rootWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
            Session["MMpageItems"] = Convert.ToInt32(rootWebConfig.AppSettings.Settings["HighScorePlayersList"].Value);
         
            AjaxPro.Utility.RegisterTypeForAjax(typeof(QualifyResultsPerMachine));
            Session["QRMTimer2"] = Convert.ToInt32(rootWebConfig.AppSettings.Settings["milisecondsToShowMachines"].Value);
            
            if (Request.QueryString["id"] != null)
            {

                int Pk_Tournament = int.Parse(Request.QueryString["id"]);
                
                List<Machine> oMachine = Machine.GetMachinesByTournament(Pk_Tournament);
                Session["QRMMACHINES"] = oMachine;
                Session["QRMTotalMachineCount2"] = oMachine.Count;
                Session["QRMPk_Tournament2"] = Pk_Tournament;
                Session["QRMp_Machine_Number2"] = 0;
                //LoadData(Pk_Tournament,0);
                oTour = new Tournament(Pk_Tournament);

            }
            else {
                Response.Write("No tournament select...");
            }

                      

        }
        catch (Exception Ex) {
            Response.Write(Ex.Message);  
        } 
     
    }
    public void LoadData(int Pk_Tournament,int MachineArrayPosition) {
        try
        {
            int ActualMachinePk = ((List<Machine>)Session["QRMMACHINES"])[MachineArrayPosition].Machine_Number;
            if (Scores == null)
            {
                Configuration rootWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
                String[] a = rootWebConfig.AppSettings.Settings["QualifyScores"].Value.Split(SCORE_DELIMITER);
                int[] ret = new int[a.Length];
                for (int i = 0; i < a.Length; i++)
                {
                    ret[i] = int.Parse(a[i]);
                }
                Scores = ret;
            }
            Tournament oTournament = new Tournament(Pk_Tournament);

            QualifyRounds oQualifyRounds = new QualifyRounds(Pk_Tournament);



            //List<QualifyRound> RoundsWithScore = oQualifyRounds.GetQualifyRoundByMachine(p_Machine_Number);
            List<QualifyRound> RoundsWithScore = oQualifyRounds.GetQualifyRoundByMachine(ActualMachinePk);
            //Calculamos los puntos


            RoundsWithScore.Sort(new ObjectComparer<QualifyRound>("Score DESC", true));

            List<Player> oPlayers = new List<Player>(); //Donde almacenamos el total;

            if (RoundsWithScore.Count > 0)
            { //Si hay puntuaciones
                int ScoreCounter = 0; // puntero a la puntuación

                //Calculamos los puntos por maquina y hacemos sumatorio

                for (int x = 0; x < RoundsWithScore.Count; x++)
                {
                    RoundsWithScore[x].PositionInRound = ScoreCounter + 1;

                    if (ScoreCounter < Scores.Length)
                    {  //si le toca puntuación
                        RoundsWithScore[x].PointsInRound = Scores[ScoreCounter];
                        //if (x > 0 && RoundsWithScore[x - 1].Score != RoundsWithScore[x].Score)
                        //{//Verificamos si no es igual a la posicion anterior
                        //    ScoreCounter++;
                        //}
                        //else if (x == 0) {
                        //    ScoreCounter++;
                        //}
                        if (RoundsWithScore[x].Score == 0) //Si está penalizado
                        {
                            RoundsWithScore[x].PointsInRound = 0;
                            RoundsWithScore[x].PositionInRound = 0;
                        }
                        else
                        {
                            if (x > 0 && RoundsWithScore[x - 1].Score != RoundsWithScore[x].Score)
                            {//Verificamos si no es igual a la posicion anterior

                                ScoreCounter++;
                            }
                            else if (x == 0)
                            {

                                ScoreCounter++;
                            }
                            else
                            {
                                //Repeticion de puntuaciones
                                RoundsWithScore[x].PointsInRound = Scores[ScoreCounter - 1];
                                RoundsWithScore[x].PositionInRound = ScoreCounter;
                            }
                        }
                    }
                    else
                    {
                        RoundsWithScore[x].PointsInRound = 0;
                        ScoreCounter++;
                    }


                }




            }

            RoundsWithScore.Sort(new ObjectComparer<QualifyRound>("Machine_Number ASC,Score DESC", true));

            Session["QRMRoundsWithScore2"] = RoundsWithScore;
            

            //HTMLOUT = drawTable(RoundsWithScore, oPlayers, Rondas, oTournament.QualifyPlayersToPlayOffs );
        }
        catch (Exception Ex) {
            string Error = Ex.ToString(); 
        }
 
    }
    public int getUniques(List<QualifyRound> things){
        Dictionary<int, bool> uniques = new Dictionary<int, bool>();  
        foreach (QualifyRound item in things){  
            if (!(uniques.ContainsKey(item.Pk_Player))){     
                uniques.Add(item.Pk_Player, true); 
            }   
        }   
        return uniques.Count ;   
    }
    

    public string drawTable(List<QualifyRound> oQualifyRounds)
    {
        try
        {
            if (oQualifyRounds.Count > 0)
            {

                StringBuilder OutPutHTML = new StringBuilder();
                //OutPutHTML.Append("<table class=\"Lotery\" style=\"width:780px;text-align:left;border:1px solid black;border-collapse: collapse; padding:5px\">");
                OutPutHTML.AppendFormat("<center><div class='Title'>Machine nº {0} - {1} ({2})</div>", oQualifyRounds[0].Machine_Number, Machine.GetMachineByMachineNumber(oQualifyRounds[0].Machine_Number, int.Parse(Session["QRMPk_Tournament2"].ToString())).Machine_Name, oQualifyRounds[0].Machine_Acron);
                OutPutHTML.Append("<table><tr><td style=\"vertical-align:top\">");
                OutPutHTML.Append("<table class=\"Lotery2\" style=\"text-align:left;margin-top:10px;border:1px solid black;border-collapse: collapse; padding:5px; width:400px\">");
                OutPutHTML.Append("<tr style=\"background-color:#ffffff;border:1px solid black; font-weight:bold\">");
                //Header
                OutPutHTML.Append("<td style='text-align:center'>Position</td>");                
                OutPutHTML.Append("<td>Player</td>");
                OutPutHTML.Append("<td style=\"text-align:right\">Score</td>");
                OutPutHTML.Append("<td style='text-align:center'>Points</td>");   

                int RowColor = 0;
                int counter = 0;
                foreach (QualifyRound iQualifyRound in oQualifyRounds)
                {
                    counter++;
                    if (counter <= 27)
                    {
                        //FIN CONTROL PAGINACION

                        if (RowColor % 2 == 0)
                        {
                            OutPutHTML.Append("<tr style=\"background-color:#e6e4e4\">");
                        }
                        else
                        {
                            OutPutHTML.Append("<tr style=\"background-color:#ffffff\">");
                        }

                        OutPutHTML.AppendFormat("<td style=\"text-align:center\">{0}º</td>", iQualifyRound.PositionInRound.ToString());
                        OutPutHTML.AppendFormat("<td><b><img style=\"vertical-align:middle;\" src=\"img/player_flags/b{0}.png\"/>&nbsp;&nbsp;&nbsp; {1}</b> (#{2})</td>", iQualifyRound.Pk_Player_Zone, iQualifyRound.Player_Nick, iQualifyRound.PlayerNumber);
                        OutPutHTML.AppendFormat("<td style=\"text-align:right\">{0}</td>", iQualifyRound.Score.ToString());
                        OutPutHTML.AppendFormat("<td style=\"text-align:center\">{0}</td>", iQualifyRound.PointsInRound.ToString());
                        OutPutHTML.Append("</tr>");
                        RowColor++;
                    }
                }


                OutPutHTML.Append("</table>");
                OutPutHTML.Append("</td><td style=\"vertical-align:top\">");
                //Second table
                OutPutHTML.Append("<table class=\"Lotery2\" style=\"text-align:left;margin-top:10px;border:1px solid black;border-collapse: collapse; padding:5px; width:400px\">");
                OutPutHTML.Append("<tr style=\"background-color:#ffffff;border:1px solid black; font-weight:bold\">");
                //Header
                OutPutHTML.Append("<td style='text-align:center'>Position</td>");
                OutPutHTML.Append("<td>Player</td>");
                OutPutHTML.Append("<td style=\"text-align:right\">Score</td>");
                OutPutHTML.Append("<td style='text-align:center'>Points</td>");

                RowColor = 0;
                counter = 0;
                foreach (QualifyRound iQualifyRound in oQualifyRounds)
                {
                    counter++;
                    if (counter > 27 && counter < 55)
                    {
                        //FIN CONTROL PAGINACION

                        if (RowColor % 2 == 0)
                        {
                            OutPutHTML.Append("<tr style=\"background-color:#e6e4e4\">");
                        }
                        else
                        {
                            OutPutHTML.Append("<tr style=\"background-color:#ffffff\">");
                        }

                        OutPutHTML.AppendFormat("<td style=\"text-align:center\">{0}º</td>", iQualifyRound.PositionInRound.ToString());
                        OutPutHTML.AppendFormat("<td><b><img style=\"vertical-align:middle;\" src=\"img/player_flags/b{0}.png\"/>&nbsp;&nbsp;&nbsp; {1}</b> (#{2})</td>", iQualifyRound.Pk_Player_Zone, iQualifyRound.Player_Nick, iQualifyRound.PlayerNumber);
                        OutPutHTML.AppendFormat("<td style=\"text-align:right\">{0}</td>", iQualifyRound.Score.ToString());
                        OutPutHTML.AppendFormat("<td style=\"text-align:center\">{0}</td>", iQualifyRound.PointsInRound.ToString());
                        OutPutHTML.Append("</tr>");
                        RowColor++;
                    }
                }

                OutPutHTML.Append("</table>");
                OutPutHTML.Append("</td></tr></table>");
               

                OutPutHTML.Append("</center>");
                return OutPutHTML.ToString();
            }
            else
            {
                //Aun no hay resultados para esa máquina va 1 por detras
                 StringBuilder OutPutHTML = new StringBuilder();
                 Machine oMachine = Machine.GetMachineByMachineNumber(((List<Machine>)Session["QRMMACHINES"])[(int)Session["QRMp_Machine_Number2"]].Machine_Number, (int)Session["QRMPk_Tournament2"]);
                //OutPutHTML.Append("<table class=\"Lotery\" style=\"width:780px;text-align:left;border:1px solid black;border-collapse: collapse; padding:5px\">");
                 OutPutHTML.AppendFormat("<center><div class='Title'>Machine nº {0} - {1} ({2})</div>", oMachine.Machine_Number, oMachine.Machine_Name, oMachine.Machine_Acron);
                OutPutHTML.Append("<table class=\"Lotery2\" style=\"text-align:left;margin-top:10px;border:1px solid black;border-collapse: collapse; padding:5px; width:400px\">");
                OutPutHTML.Append("<tr style=\"background-color:#ffffff;border:1px solid black; font-weight:bold\">");
                //Header
                OutPutHTML.Append("<td style='text-align:center'>Position</td>");
                OutPutHTML.Append("<td>Player</td>");
                OutPutHTML.Append("<td style=\"text-align:right\">Score</td>");
                OutPutHTML.Append("<td style='text-align:center'>Points</td>");
                OutPutHTML.Append("</tr>");
                OutPutHTML.Append("</table></center>");
                
                 return OutPutHTML.ToString();
            }        


                                          

        }
        catch (Exception Ex) {
            return Ex.ToString();
        } 
    }

    [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
    public string GetTable()
    {
        try
        {


            LoadData((int)Session["QRMPk_Tournament2"], (int)Session["QRMp_Machine_Number2"]);


            string res = drawTable((List<QualifyRound>)Session["QRMRoundsWithScore2"]);

            Session["QRMp_Machine_Number2"] = ((int)Session["QRMp_Machine_Number2"]) + 1;
            //if ((int)Session["QRMTotalMachineCount2"] == (int)Session["QRMp_Machine_Number2"])
            if ((int)Session["QRMTotalMachineCount2"] == (int)Session["QRMp_Machine_Number2"])            
            {
                Session["QRMp_Machine_Number2"] = 0;
            }
            


            return res;
        }
        catch(Exception Ex)
        {
            return Ex.ToString(); 
            //return string.Empty;
        }
    }
}

